package io.github.wanggit.antrpc.console.web.vo;

import io.github.wanggit.antrpc.console.web.utils.TimeFormatUtil;
import lombok.Data;
import org.elasticsearch.search.SearchHit;

import java.io.Serializable;
import java.util.Map;

@Data
public class CallLogsVO implements Serializable {

    private static final long serialVersionUID = -375998149845101848L;

    private String appName;

    private String caller;

    private String previousStackTrace;

    private String targetClassName;

    private String date;

    private String targetMethodName;

    private String requestArgs;

    private String ipAndPort;

    private String targetIpAndPort;

    private String requestId;

    private Integer rt;

    private String serialNumber;

    private String targetAppName;

    public static CallLogsVO from(SearchHit searchHit) {
        CallLogsVO callLogsVO = new CallLogsVO();
        Map<String, Object> sourceAsMap = searchHit.getSourceAsMap();
        callLogsVO.setAppName(getValueOrDefault(sourceAsMap, "appName", null));
        callLogsVO.setCaller(getValueOrDefault(sourceAsMap, "caller", null));
        callLogsVO.setPreviousStackTrace(
                getValueOrDefault(sourceAsMap, "previousStackTrace", null));
        callLogsVO.setTargetClassName(getValueOrDefault(sourceAsMap, "targetClassName", null));
        callLogsVO.setDate(
                TimeFormatUtil.tzDateFormat(getValueOrDefault(sourceAsMap, "date", null)));
        callLogsVO.setTargetIpAndPort(
                getValueOrDefault(sourceAsMap, "targetIp", null)
                        + ":"
                        + getValueOrDefault(sourceAsMap, "targetPort", null));
        callLogsVO.setIpAndPort(
                getValueOrDefault(sourceAsMap, "ip", null)
                        + ":"
                        + getValueOrDefault(sourceAsMap, "port", null));
        callLogsVO.setTargetMethodName(getValueOrDefault(sourceAsMap, "targetMethodName", null));
        callLogsVO.setRequestArgs(getValueOrDefault(sourceAsMap, "requestArgs", null));
        callLogsVO.setRequestId(getValueOrDefault(sourceAsMap, "requestId", null));
        callLogsVO.setRt(Integer.parseInt(getValueOrDefault(sourceAsMap, "rt", "-1")));
        callLogsVO.setSerialNumber(getValueOrDefault(sourceAsMap, "serialNumber", null));
        callLogsVO.setTargetAppName(getValueOrDefault(sourceAsMap, "targetAppName", null));
        return callLogsVO;
    }

    private static String getValueOrDefault(
            Map<String, Object> sourceAsMap, String key, String defaultValue) {
        if (null != sourceAsMap.get(key)) {
            return sourceAsMap.get(key).toString();
        }
        return defaultValue;
    }
}
